<template>
	<view class="page-cont" :style="themeStore.theme">
		<image class="bg-cont" src="/static/home_back.jpg"></image>
		<view class="header-cont">
			<view class="stat-cont">
				<view class="stat-top">
					<view class="stat-top-company">{{userInfo.companyName}}</view>
					<view class="stat-top-logo">
						<image class="stat-top-logo-bg" src="/static/home_logo.png"></image>
						<image class="stat-top-logo-img" :src="userInfo.companyLogo" mode="aspectFit"></image>
					</view>
				</view>
				<view class="stat-bottom">
					<view class="stat-left">
						<view :class="['stat-box', statActive == 0 ? 'stat-box-active' : '']"
							@click="handleStatClick(0)">
							<view class="stat-box-value">{{statData.total}}</view>
							<view class="stat-box-title">全部项目</view>
						</view>
					</view>
					<view class="stat-right">
						<view :class="['stat-box', statActive == 1 ? 'stat-box-active' : '']"
							@click="handleStatClick(1)">
							<view class="stat-box-value">{{statData.offCount}}</view>
							<view class="stat-box-title">离线</view>
						</view>
						<view :class="['stat-box', statActive == 2 ? 'stat-box-active' : '']"
							@click="handleStatClick(2)">
							<view class="stat-box-value">{{statData.alarmCount}}</view>
							<view class="stat-box-title">报警</view>
						</view>
					</view>
				</view>
			</view>
			<view class="search-cont">
				<input class="search-cont-input" placeholder="请输入项目名称" v-model="keyword" />
				<image class="search-cont-icon" src="/static/home_search.png" @click="handleQuery"></image>
			</view>
		</view>
		<scroll-view class="scroll-cont" scroll-y refresher-enabled :refresher-triggered="isRefresh"
			@refresherrefresh="handlePullDownRefresh">
			<view class="list-cont">
				<view class="list-item" v-for="(item, index) in projectList" :key="index"
					@click="handleDetailClick(item)">
					<view class="list-item-top">
						<view class="list-item-project-name">{{item.name}}</view>
						<view
							:class="['iconfont icon-juxing', item.wc > 0 ? 'status-warn' : item.ds <= 0 ? 'status-offline' : 'status-normal']">
						</view>
						<view class="status-text">{{item.wc > 0 ? `异常预警:${item.wc}个` : '运行正常'}}</view>
						<image v-if="item.isTop" class="list-item-tag-name" src="/static/home_top.png"></image>
						<view class="list-item-data">
							<view class="list-item-data-area">面积：<text
									class="list-item-data-num">{{item.acreage || 0}}㎡</text></view>
							<view class="list-item-data-elec">昨日耗能：<text
									class="list-item-data-num">{{item.pw || 0}}kWh</text></view>
						</view>
					</view>
					<view class="list-item-bottom">
						<view class="list-item-location">
							<image class="list-item-location-icon" src="/static/home_position.png"></image>
							<view class="list-item-location-city">{{item.province}}</view>
						</view>
						<view class="list-item-btn">
							<view class="list-item-btn-detail" @click.stop="handleScreenClick(item)">查看组态</view>
							<view v-if="item.isTop" class="list-item-btn-tag" @click.stop="handleCancelTop(item)">取消置顶
							</view>
							<view v-else class="list-item-btn-tag" @click.stop="handleProjectTop(item)">置顶</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>
<script setup lang="ts">
	import { ref, reactive, computed, watch } from "vue";
	import { storeToRefs } from 'pinia';
	import useThemeStore from '@/store/theme';
	import useUserStore from '@/store/user';
	import useHomeStore from '@/store/home';
	import { useNavbar } from "@/utils/hooks.js";
	import { userConf } from "@/api/login.js";
	import { getProjectList, getProjectModel, getProjectStat, getDeviceStatus, updateProjectTop } from "@/api/home.js";
	const { pageCustomHeight } = useNavbar();
	const themeStore = useThemeStore();
	const homeStore = useHomeStore();
	const userStore = useUserStore();
	const { userInfo } = storeToRefs(userStore);
	const projectConfig = ref([])
	const isRefresh = ref(false)
	const statActive = ref(0)
	const statData = ref({
		alarmCount: 0,//报警数
		offCount: 0,//离线数量
		total: 0,//项目总数
	});
	const keyword = ref("");
	const queryParams = ref({
		// isAll: true,
		// isOffline: null,
		// isAlarm: null,
		// keyword: null
	}) //查询参数
	const projectList = ref([{
		name: '',
		status: '',
		acreage: '',
		pw: '',
		province: '',
		isTop: false, //是否置顶
		wc: 0, //设备报警数量
		ds: 0, //设备在线数量
		dc: 0, //设备总数
	}])

	initData()

	async function initData() {
		homeStore.clearProjectData();//清空项目数据
		await getStatData()
		await getProjectData()
		await getUserConfig();
		handleProjectSort();
		isRefresh.value = false;
	}

	// 项目统计
	function getStatData() {
		return new Promise(resolve => {
			getProjectStat().then(res => {
				let arr = res.data || [];
				if (arr.length) {
					statData.value = arr[0];
				}
				resolve(true);
			});
		});
	}

	// 项目列表
	function getProjectData() {

		switch (statActive.value) {
			case 0:
				queryParams.value = { isAll: true, keyword: keyword.value };
				break;
			case 1:
				queryParams.value = { isOffline: true, keyword: keyword.value };
				break;
			case 2:
				queryParams.value = { isAlarm: true, keyword: keyword.value };
				break;
		}

		return new Promise(resolve => {
			getProjectList(queryParams.value).then(res => {
				let arr = res.data || [];
				arr.forEach(element => {
					element.isTop = false;
				});
				projectList.value = arr;
				resolve(true);
			});
		});
	}

	// 项目置顶
	function setProjectTop(mid) {
		return new Promise(resolve => {
			updateProjectTop({ mid: mid }).then(() => {
				resolve(true);
			});
		});
	}

	// 获取项目置顶配置
	function getUserConfig() {
		return new Promise(resolve => {
			userConf({ key: `app_pm_${userInfo.value.id}` }).then(res => {
				projectConfig.value = decodeURIComponent(res.data || "").split(",");
				resolve(true);
			});
		});
	}

	// 存储项目信息
	function setUserConfig() {
		return new Promise(resolve => {
			let arr = projectList.value.filter(element => element["isTop"]);
			// console.log("arr ",arr)
			let idArr = arr.map(element => element["id"]);//获取置顶项目的id
			// console.log("idArr ",idArr)
			userConf({ key: `app_pm_${userInfo.value.id}`, conf: idArr.length ? idArr.join(",") : "null" }).then(() => {
				resolve(true);
			});
		});
	}

	// 项目置顶
	async function handleProjectTop(e) {
		e.isTop = true;
		await setProjectTop(e.id);
		await setUserConfig();
		await getUserConfig();
		await getProjectData()
		handleProjectSort();
	}

	// 取消置顶
	async function handleCancelTop(e) {
		e.isTop = false;
		await setUserConfig();
		await getUserConfig();
		await getProjectData()
		handleProjectSort();
	}

	function handleProjectSort() {
		if (!projectConfig.value.length) {
			return;
		}
		// 排序
		projectList.value.sort((a, b) => {
			return projectConfig.value.indexOf(b["id" + ""]) - projectConfig.value.indexOf(a["id"] + "");
		});
		// 置顶标记
		projectList.value.forEach(element => {
			if (projectConfig.value.indexOf(element["id"] + "") !== -1) {
				element.isTop = true;
			}
		});
	}

	// 下拉刷新
	const handlePullDownRefresh = () => {
		isRefresh.value = true;
		initData();
	}

	// 项目：离线、报警筛选
	function handleStatClick(e) {
		statActive.value = e;
		// queryParams.value.isAll = null;
		// queryParams.value.isOffline = null;
		// queryParams.value.isAlarm = null;
		// if (e == 0) {
		// 	// 全部
		// 	queryParams.value = { isAll: true };
		// } else if (e == 1) {
		// 	// 离线
		// 	queryParams.value = { isOffline: true };
		// } else if (e == 2) {
		// 	// 报警
		// 	queryParams.value = { isAlarm: true };
		// }
		// getProjectData()
		initData();
	}

	// 项目详情
	function handleDetailClick(e) {
		homeStore.setProjectId(e.id);//保存项目id
		homeStore.setProjectName(e.name);//保存项目名称
		uni.navigateTo({
			url: '/pages/home/detail',
		});
	}

	// 查看组态
	function handleScreenClick(e) {
		homeStore.setProjectId(e.id);//保存项目id
		homeStore.setProjectName(e.name);//保存项目名称
		uni.navigateTo({
			url: '/pages/screen/index',
		});
	}

	// 查询
	function handleQuery() {
		getProjectData();
	}
</script>
<style lang="scss" scoped>
	.page-cont {
		position: relative;
		padding: 65px 20px 20px;
		height: 100%;
		box-sizing: border-box;

		.bg-cont {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 180px;
		}

		.header-cont {
			position: relative;
			z-index: 100;
		}

		.stat-cont {
			background-color: $theme-color;

			.stat-top {
				display: flex;
				justify-content: space-between;
			}

			.stat-top-company {
				width: calc(100% - 155px);
				padding: 0 10px;
				height: 55px;
				line-height: 55px;
				color: #fff;
				font-size: 14px;
				font-weight: 600;
			}

			.stat-top-logo {
				position: relative;
				width: 155px;
				height: 55px;
				display: flex;
				justify-content: flex-end;

				.stat-top-logo-bg {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
				}

				.stat-top-logo-img {
					position: relative;
					padding-top: 10px;
					width: 100px;
					height: 30px;
					z-index: 100;
				}
			}

			.stat-bottom {
				padding: 0 10px 10px;
				display: flex;
				box-sizing: border-box;

				.stat-left,
				.stat-right {
					width: 50%;
					height: 60px;
				}

				.stat-left {
					position: relative;
					display: flex;
					justify-content: center;
					align-items: center;

					&::before {
						content: '';
						position: absolute;
						top: 13px;
						right: 5px;
						width: 1px;
						height: 25px;
						background-color: rgba(255, 255, 255, 0.5);
					}
				}

				.stat-right {
					display: flex;
					align-items: center;
				}

				.stat-box {
					width: 50%;
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					border-radius: 5px;
				}

				.stat-box-value,
				.stat-box-title {
					color: #fff;
					font-size: 17px;
					line-height: 1;
					font-weight: 600;
				}

				.stat-box-title {
					padding-top: 5px;
					font-size: 11px;
					line-height: 1;
				}

				.stat-box-active {
					background-color: rgba(0, 0, 0, 0.1);

					.stat-box-value {
						font-size: 25px;
						line-height: 1;
					}

					.stat-box-title {
						font-size: 14px;
						line-height: 1;
					}
				}
			}
		}

		.scroll-cont {
			height: calc(100% - 185px);
		}

		.search-cont {
			margin-top: 10px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-radius: 5px;
			background-color: #fff;

			.search-cont-input {
				padding: 0 20px;
				width: calc(100% - 50px);
				box-sizing: border-box;
			}

			.search-cont-icon {
				padding: 15px;
				width: 50px;
				height: 50px;
				box-sizing: border-box;
			}

			::v-deep .uni-easyinput__content {
				border: none !important;
			}
		}

		.list-cont {
			position: relative;
			margin-top: 15px;
			z-index: 100;

			.list-item {
				margin-top: 15px;
				border-radius: 5px;
				background-color: $theme-color;

				&:first-child {
					margin-top: 0;
				}
			}

			.list-item-top {
				position: relative;
				padding: 10px;
			}

			.list-item-bottom {
				padding: 0 15px;
				height: 40px;
				display: flex;
				align-items: center;
				border-top: 1px solid #fff;
			}

			.list-item-project-name {
				width: calc(100% - 100px);
				color: #fff;
				font-size: 14px;
				font-weight: 600;
			}

			.status-normal,
			.status-warn,
			.status-offline,
			.status-text {
				position: absolute;
				top: 0;
				right: 0;
				width: 100px;
				height: 30px;
				line-height: 30px;
				color: #1FD4CD;
				font-size: 30px;
				text-align: right;
			}

			.status-warn {
				color: #FF6E8A;
				transform: scaleX(2);
			}

			.status-offline {
				color: #A1BCD2;
			}

			.status-text {
				padding: 0 10px;
				color: #fff;
				font-size: 13px;
				font-weight: 600;
				z-index: 100;
				// padding-left: 25rpx;
				// background-image: url('/static/home_top.png');
			}

			.list-item-tag-name {
				position: absolute;
				top: 40px;
				right: 0;
				width: 50px;
				height: 25px;
			}

			.list-item-data {
				margin-top: 40px;
				display: flex;
			}

			.list-item-data-area,
			.list-item-data-elec {
				position: relative;
				width: 50%;
				display: flex;
				align-items: center;
				color: rgba(255, 255, 255, 0.8);
				font-size: 13px;
				font-weight: 600;
			}

			.list-item-data-elec::before {
				content: '';
				position: absolute;
				top: 0;
				left: -20px;
				width: 1px;
				height: 100%;
				background-color: rgba(255, 255, 255, 0.4);
			}

			.list-item-data-num {
				color: #fff;
			}

			.list-item-location {
				width: 50%;
				height: 100%;
				line-height: 40px;
				display: flex;
				align-items: center;
			}

			.list-item-location-icon {
				width: 15px;
				height: 15px;
			}

			.list-item-location-city {
				padding-left: 5px;
				color: #fff;
				font-size: 13px;
				font-weight: 600;
			}

			.list-item-btn {
				width: 50%;
				height: 100%;
				line-height: 40px;
				display: flex;
				align-items: center;
			}

			.list-item-btn-detail,
			.list-item-btn-tag {
				color: #fff;
				font-size: 11px;
				font-weight: 600;
			}

			.list-item-btn-tag {
				padding-left: 43px;
			}
		}
	}
</style>